<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }
  *{
    list-style:none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
  input.time {
    border: none;
    font-size: 16px;
    padding-left: 10px;
  }

</style>
<template>
  <div class="addplan">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      录入生产计划
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">名称</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" v-model="pname" name="name" placeholder="请输入计划名称" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">库房</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="strmid" v-model="strmid">
                <option value="" disabled>请选择库房</option>
                <option v-for="(item, index) in storerooms" :key="item.srguid" :value="item.srguid">{{item.storeName}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">计划类型</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="type" :value="type" />
              <select class="weui-select" name="type" v-model="type" disabled>
                <option v-for="(item, index) in types" :value="item.dictkey" >{{item.dicttext}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">生产日期</label></div>
            <div class="weui-cell__bd">
              <input type="text" id='datetime-picker' class="time" name="planstart" placeholder="请选择开始时间" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="remarks" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>

        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
          <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'AddProduceplan',
    data () {
      return {
        openid: localStorage.openid,
        storerooms: [],
        organizations: [],
        orgid: '',
        products: [],
        specifications0: [],
        specifications1: [],
        specifications2: [],
        specifications3: [],
        specifications4: [],
        strmid: '',
        pricemodes: [],
        pricemode: '',
        types: [],
        type: 1,
        pname: ''
      }
    },
    created() {
      window.addEventListener('setItem', ()=> {
        this.openid = localStorage.getItem('openid');
      })
    },
    mounted () {
      let that = this;

      $("#datetime-picker").calendar();
      $("#datetime-picker2").calendar();

      //获取包工计价方式
      this.getTypes()
      //获取组织
      this.getOrganization()
      //获取库房
      this.getStoreRoom()

      //this.getProduct()
      //获取规格
      //this.getSpecif()

      //添加明细item
      // $('form').on('click', '#addItem', function () {
      //   $('.oitem:hidden').eq(0).find('input').attr("disabled",false);
      //   $('.oitem:hidden').eq(0).find('textarea').attr("disabled",false);
      //   $('.oitem:hidden').eq(0).find('select').attr("disabled",false);
      //   $('.oitem:hidden').eq(0).show();
      //   updateActBtns();
      // })
      // //删除明细
      // $('form').on('click', '#delItem', function () {
      //   var elm = $(this).parents('.oitem');
      //   $.confirm("确定要删除该货品明细吗？", function () {
      //     elm.find('input').val('');
      //     elm.find('textarea').val('');
      //     elm.hide();
      //     $('.oitem:hidden').eq(0).find('input').attr("disabled",true);
      //     $('.oitem:hidden').eq(0).find('textarea').attr("disabled",true);
      //     $('.oitem:hidden').eq(0).find('select').attr("disabled",true);
      //     updateActBtns();
      //   })
      // })
      //调整添加、删除按钮位置
      function updateActBtns() {
        $('#acts').remove();
        var actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="addItem" style="padding-right: 5px;">添加</span><span>|</span><span id="delItem" style="padding-left: 5px;">删除</span></p>';

        if ($('.oitem:visible').length == 5) {
          actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="delItem" style="padding-left: 5px;">删除</span></p>';
        } else if ($('.oitem:visible').length == 1) {
          var actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="addItem" style="padding-right: 5px;">添加</span></p>';
        }
        $('.oitem:visible:last').find('.weui-cells__title').append(actHtml);
      }

      //产品、规格名称表单提交
      $('.product').change(function () {
        let product = $(this).find('option:selected').text();
        $(this).prev().val(product);
        that.getSpecif($(this).val(), $(this).data('index'));
      })
      $('.specif').change(function () {
        let specif = $(this).find('option:selected').text();
        $(this).prev().val(specif);
      })
    },
    watch: {
      'strmid': function (val) {
        const str = this.storerooms.filter(item =>{
          return item.srguid == val;
        })[0] || {};
        this.type = str.flag;
      }
    },
    methods: {
      getTypes: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Sellform!findDict.action',
          params: {type: 96}
        }).then(response => {
          if (response.statusText == "OK") {
            that.types = response.data;
          } else {
            this.toastText('获取类型数据失败');
          }
        });
      },
      getPricemode: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 35}
        }).then(response => {
          if (response.statusText == "OK") {
            that.pricemodes = response.data;
            this.pricemode = response.data[0].dictkey;
          } else {
            this.toastText('获取包工计价方式数据失败');
          }
        });
      },
      getOrganization: function() {
        this.axios({
          method: 'get',
          url: '/produce/Produceplan!getOrgbyWh.action',
          params: {}
        }).then((response) => {
          if (response.data.status == 'true') {
            this.organizations = response.data.result;
            this.orgid = response.data.result[0].guid;
          } else if(response.data.status == 'false') {
            this.toastText(response.data.result);
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getStoreRoom: function() {
        this.axios({
          method: 'get',
          url: '/produce/Produceplan!getSrbyWh.action',
        }).then((response) => {
          if (response.data.status == 'true') {
            this.storerooms = response.data.result;
            this.strmid = response.data.result.length > 0 ? response.data.result[0].srguid : this.strmid;
          } else if(response.data.status == 'false') {
            this.toastText(response.data.result);
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getProduct: function() {
        if (this.orgid == '' || this.strmid == '') return;
        this.axios({
          method: 'get',
          url: '/sales/Sellform!findProductinfoBYStr.action?guid=' + this.strmid,
          params: {orgguid: this.orgid}
        }).then((response) => {
          if (response.data.status == 'true') {
            this.products = response.data.result;
          } else if(response.data.status == 'false') {
            this.toastText(response.data.result);
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getSpecif: function(productid, index) {
        this.axios({
          method: 'get',
          url: '/produce/Whinapply!getSpeByproduct.action',
          params: {productid: productid, stats: '1,4'}
        }).then((response) => {
          if (response.data.msg == 'success') {
            let data = response.data;
            this['specifications' + index] = data.specifications.filter(item => {
              return item.status == 1;
            });
          } else {
            this.toastError("系统错误");
          }

        })
      },
      send: function() {
        let that = this;

        if(!checkSubmit(this)){
          return;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        this.axios({
          method: 'post',
          url: '/produce/Produceplan!saveOrUpdate.action',
          //params: $("#formid").serialize()
          params: this.serialize2Obj($("#formid").serializeArray())
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if(response.data.status == "true"){
            this.toastText('操作成功!');
            this.$router.push({name: 'ProduceplanList'});
          }else if (response.data.status == 'false'){
            this.toastText(response.data.result);
          }else {
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });

      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i=0; i<$('.product').not(':hidden').length; i++) {
          parr1.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
          parr2.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j =i+1; j <parr2.length; ) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0] ) {
              parr2.splice(j, 1);//去除重复的对象；
            }else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      }
    }
  }
  /**
   * 提交之前的校验
   */
  function checkSubmit(that){
    if(that.pname == ''){
        $.alert("请录入计划名称！");
        return false;
    } else if(that.strmid == ''){
      $.alert("请选择库房！");
      return false;
    } else if($('input[name="weight"]').val() == ''){
      $.alert("请输入总重量！");
      return false;
    } else if($('input[name="planstart"]').val() == ''){
      $.alert("请选择生产日期！");
      return false;
    }

    return true;
  }

</script>
